import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:hongsheng/model/SPClassLeagueFilter.dart';
import 'package:hongsheng/pages/common/SPClassNoDataView.dart';
import 'package:hongsheng/pages/home/SPClassHomePage.dart';
import 'package:hongsheng/utils/SPClassCommonMethods.dart';
import 'package:hongsheng/utils/SPClassImageUtil.dart';
import 'package:hongsheng/utils/SPClassStringUtils.dart';
import 'package:hongsheng/utils/SPClassToastUtils.dart';
import 'package:hongsheng/api/SPClassApiManager.dart';
import 'package:hongsheng/utils/colors.dart';
import 'package:hongsheng/api/SPClassHttpCallBack.dart';
import 'package:hongsheng/widgets/SPClassBallHeader.dart';
import 'package:hongsheng/widgets/SPClassToolBar.dart';


class SPClassLeaguePage extends StatefulWidget {
  final String ?selectLeagueName;
  final String ?expertId;
  final String ?selectTime;

  SPClassLeaguePage({Key ?key,this.selectLeagueName,this.expertId,this.selectTime}) : super(key: key);

  @override
  _SPClassLeaguePageState createState() => _SPClassLeaguePageState();
}

class _SPClassLeaguePageState extends State<SPClassLeaguePage> {
  EasyRefreshController controller = EasyRefreshController();
  List<List<SPClassLeagueName>> spProListValue = [];
  List<String> spProListKeys = [];
  String selectLeagueName = '全部';
  bool spProSelectAll=false;
  bool spProSelectAllNot=false;
  List selectLeagueList =[];

  @override
  void initState() {
    selectLeagueName =widget.selectLeagueName!;
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: SPClassToolBar(
        context,
        title: "赛事筛选",
        actions: <Widget>[
          widget.expertId!=null?Container():GestureDetector(
            behavior: HitTestBehavior.opaque,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: width(20)),
              alignment: Alignment.center,
              child: Text("确定",style: TextStyle(color: MyColors.main1,fontSize: sp(16)),),
            ),
            onTap: (){
              Navigator.pop(context,selectLeagueName);
            },
          )

        ],
      ),
      body: EasyRefresh.custom(
        controller: controller,
        onRefresh: spFunOnRefresh,
        firstRefresh: true,
        header: SPClassBallHeader(textColor: Color(0xFF666666)),
        emptyWidget: spProListValue.length == 0 ? SPClassNoDataView() : null,
        slivers: <Widget>[
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                var key = spProListValue[index];

                return Container(
                  padding: EdgeInsets.only(left: width(15), right: width(15)),
                  child: Column(
                    children: <Widget>[
                      Container(
                        margin:
                            EdgeInsets.only(top: height(15), bottom: height(5)),
                        alignment: Alignment.centerLeft,
                        child: Text(
                          key[0].spProPinyinInitial.toString(),
                          style: TextStyle(
                              fontSize: sp(13), color: Color(0xFF333333)),
                        ),
                      ),
                      GridView.count(
                        crossAxisCount: 3,
                        shrinkWrap: true,
                        crossAxisSpacing: width(11),
                        mainAxisSpacing: height(9),
                        physics: NeverScrollableScrollPhysics(),
                        childAspectRatio: width(103) / width(27),
                        children: key.map((item) {
                          return widget.expertId==null? GestureDetector(
                            child: Container(
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border.all(
                                      width: 0.4,
                                      color: selectLeagueName==item.spProLeagueName
                                          ? Color(0xFFDE3C31)
                                          : Color(0xFFCCCCCC)),
                                  borderRadius:
                                      BorderRadius.circular(width(3))),
                              child: Row(
                                children: <Widget>[
                                  SizedBox(
                                    width: width(9),
                                  ),
                                  Image.asset(
                                      SPClassImageUtil.spFunGetImagePath(
                                          "ic_check_box"),
                                      width: width(13),
                                      color: selectLeagueName==item.spProLeagueName
                                          ? Color(0xFFDE3C31)
                                          : Color(0xFFCCCCCC)),
                                  SizedBox(
                                    width: width(3),
                                  ),
                                  Expanded(
                                    child: Row(
                                      children: <Widget>[
                                        Text(
                                    item.spProLeagueName=='all'?'全部': "${SPClassStringUtils.spFunMaxLength(item.spProLeagueName??'', length: 4)}",
                                          style: TextStyle(
                                              fontSize: sp(11),
                                              color: selectLeagueName==item.spProLeagueName
                                                  ? Color(0xFFDE3C31)
                                                  : Color(0xFF333333)),
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                        )
                                      ],
                                    ),
                                  ),
                                  SizedBox(
                                    width: width(3),
                                  ),
                                ],
                              ),
                            ),
                            onTap: () {
                              selectLeagueName = item.spProLeagueName!;
                              setState(() {

                              });
                            },
                          ):
                          GestureDetector(
                            child: Container(
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border: Border.all(
                                      width: 0.4,
                                      color: item.check
                                          ? Color(0xFFDE3C31)
                                          : Color(0xFFCCCCCC)),
                                  borderRadius:
                                  BorderRadius.circular(width(3))),
                              child: Row(
                                children: <Widget>[
                                  SizedBox(
                                    width: width(9),
                                  ),
                                  Image.asset(
                                      SPClassImageUtil.spFunGetImagePath(
                                          "ic_check_box"),
                                      width: width(13),
                                      color: item.check
                                          ? Color(0xFFDE3C31)
                                          : Color(0xFFCCCCCC)),
                                  SizedBox(
                                    width: width(3),
                                  ),
                                  Expanded(
                                    child: Row(
                                      children: <Widget>[
                                        Text(
                                          "${SPClassStringUtils.spFunMaxLength(item.spProLeagueName!, length: 4)}",
                                          style: TextStyle(
                                              fontSize: sp(11),
                                              color: item.check
                                                  ? Color(0xFFDE3C31)
                                                  : Color(0xFF333333)),
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                        )
                                      ],
                                    ),
                                  ),
                                  SizedBox(
                                    width: width(3),
                                  ),
                                ],
                              ),
                            ),
                            onTap: () {
                              item.check=!item.check;
                              setState(() {
                              });
                            },
                          );
                        }).toList(),
                      )
                    ],
                  ),
                );
              },
              childCount: spProListValue.length,
            ),
          ),
        ],
      ),
      bottomNavigationBar: widget.expertId!=null?Container(
        height: height(50),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(top: BorderSide(width: 0.4,color: Colors.grey[300]!))
        ),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Row(
                children: <Widget>[
                  SizedBox(width: width(14),),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    child: Row(
                      children: <Widget>[
                        Image.asset(SPClassImageUtil.spFunGetImagePath("ic_check_box"), width: width(13),color:spProSelectAll?  Color(0xFFDE3C31): Color(0xFFCCCCCC)),
                        SizedBox(width: width(3),),
                        Text("全选",style: TextStyle(fontSize: sp(13),color:spProSelectAll?  Color(0xFFDE3C31): Color(0xFF333333)),maxLines: 1,overflow: TextOverflow.ellipsis,),
                      ],
                    ),
                    onTap: (){
                      if(!spProSelectAll){
                        setState(() {
                          spProSelectAllNot=false;
                          spProSelectAll=true;
                        });
                        spFunCalcCheckCount(isBtn: true);
                      }

                    },
                  ),
                  SizedBox(width: width(13),),
                  Container(
                    width: 1,
                    height: height(9),
                    color: Colors.grey[300],
                  ),
                  SizedBox(width: width(13),),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    child: Row(
                      children: <Widget>[
                        Image.asset(SPClassImageUtil.spFunGetImagePath("ic_check_box"), width: width(13),color:spProSelectAllNot?  Color(0xFFDE3C31): Color(0xFFCCCCCC)),
                        SizedBox(width: width(3),),
                        Text("反选",style: TextStyle(fontSize: sp(13),color:spProSelectAllNot?  Color(0xFFDE3C31): Color(0xFF333333)),maxLines: 1,overflow: TextOverflow.ellipsis,),
                      ],
                    ),
                    onTap: (){
                      if(!spProSelectAllNot){
                        setState(() {
                          spProSelectAllNot=true;
                          spProSelectAll=false;
                        });
                        spFunCalcCheckCount(isBtn: true);
                      }

                    },
                  ),

                ],
              ),
            ),
            GestureDetector(
              behavior: HitTestBehavior.opaque,

              child: Container(
                alignment: Alignment.center,
                width: width(100),
                height: height(50),
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        colors: [
                          Color(0xFFF2150C),
                          Color(0xFFF24B0C)
                        ]
                    )
                ),
                child: Text("确定",style: TextStyle(color: Colors.white,fontSize: sp(16)),),
              ),
              onTap: (){
                selectLeagueList.clear();
                spProListValue.forEach((list){
                  list.forEach((item){
                    if(item.check){
                      selectLeagueList.add(item.spProLeagueName);
                    }
                  });
                });
                if(selectLeagueList.isEmpty){
                  SPClassToastUtils.spFunShowToast(msg:"请选择赛事");
                  return;
                }else{
                  Navigator.pop(context,selectLeagueList.join(','));
                }

              },
            )
          ],
        ),
      ):null,
    );
  }

  Future<void> spFunOnRefresh() async {

    if(widget.expertId!=null){
      await SPClassApiManager.spFunGetInstance().spFunGetLeagueListByExpert<
          SPClassLeagueFilter>(
          params: {
            'expert_uid':widget.expertId,
            'ranking_type':widget.selectTime
          },
          spProCallBack: SPClassHttpCallBack(spProOnSuccess: (result) {
            controller.finishLoad(success: true);
            controller.resetRefreshState();
            if (result.spProLeagueList != null &&
                result.spProLeagueList.length > 0) {
              // spProListKeys.clear();
              spProListValue.clear();
              result.spProLeagueList.forEach((item) {
                if (item.spProIsHot != null && item.spProIsHot == "1") {
                  item.spProPinyinInitial = "热";
                }
                if (item.spProPinyinInitial!.isEmpty) {
                  item.spProPinyinInitial = "#";
                }
                if (spProListKeys.indexOf(item.spProPinyinInitial!) == -1) {
                  spProListKeys.add(item.spProPinyinInitial!);
                  spProListValue.add([]);
                }
                if (result.spProHotLeagueList != null &&
                    result.spProHotLeagueList.length > 0) {
                  if (!result.spProHotLeagueList.contains(item.spProLeagueName)) {
                    spProListValue[spProListKeys.indexOf(item.spProPinyinInitial!)]
                        .add(item);
                  }
                } else {
                  spProListValue[spProListKeys.indexOf(item.spProPinyinInitial!)]
                      .add(item);
                }
                if(widget.selectLeagueName=='all'){
                  item.check=true;
                }else{
                  selectLeagueList = widget.selectLeagueName!.split(',');
                  for(int i=0;i<selectLeagueList.length;i++){
                    if(item.spProLeagueName==selectLeagueList[i]){
                      item.check=true;
                    }
                  }
                }
              });
              spProListValue.removeWhere((deleteItem) => deleteItem.length == 0);
              spProListValue.sort((left, right) {
                if (left[0].spProPinyinInitial == "热") {
                  return -1;
                }
                if (right[0].spProPinyinInitial == "热") {
                  return 1;
                }
                return left[0]
                    .spProPinyinInitial
                    !.codeUnitAt(0)
                    .compareTo(right[0].spProPinyinInitial!.codeUnitAt(0));
              });


              setState(() {});
            }
          }, onError: (value) {
            controller.finishLoad(success: false);
          }));
    }else{
      await SPClassApiManager.spFunGetInstance().spFunGetAllLeague<
          SPClassLeagueFilter>(
          params: {
            'match_type':SPClassHomePageState.spProHomeMatchTypeKey=='is_zq_expert'? '足球':'篮球',
          },
          spProCallBack: SPClassHttpCallBack(spProOnSuccess: (result) {
            controller.finishLoad(success: true);
            controller.resetRefreshState();
            if (result.spProLeagueList != null &&
                result.spProLeagueList.length > 0) {
              // spProListKeys.clear();
              spProListValue.clear();
              result.spProLeagueList.forEach((item) {
                if (item.spProIsHot != null && item.spProIsHot == "1") {
                  item.spProPinyinInitial = "热";
                  // if(widget.spProIsHot){
                  //   item.check=true;
                  // }
                }
                if (item.spProPinyinInitial!.isEmpty) {
                  item.spProPinyinInitial = "#";
                }

                if (spProListKeys.indexOf(item.spProPinyinInitial!) == -1) {
                  spProListKeys.add(item.spProPinyinInitial!);
                  spProListValue.add([]);
                }
                if (result.spProHotLeagueList != null &&
                    result.spProHotLeagueList.length > 0) {
                  if (!result.spProHotLeagueList.contains(item.spProLeagueName)) {
                    spProListValue[spProListKeys.indexOf(item.spProPinyinInitial!)]
                        .add(item);
                  }
                } else {
                  spProListValue[spProListKeys.indexOf(item.spProPinyinInitial!)]
                      .add(item);
                }
              });
              spProListValue.removeWhere((deleteItem) => deleteItem.length == 0);
              spProListValue.sort((left, right) {
                if (left[0].spProPinyinInitial == "热") {
                  return -1;
                }
                if (right[0].spProPinyinInitial == "热") {
                  return 1;
                }
                return left[0]
                    .spProPinyinInitial
                    !.codeUnitAt(0)
                    .compareTo(right[0].spProPinyinInitial!.codeUnitAt(0));
              });
              Map<String, dynamic> map ={'is_hot':'1',"league_name":"all","pinyin_initial":"热"};
              spProListValue[0].insert(0, SPClassLeagueName(json:map));

              setState(() {});
            }
          }, onError: (value) {
            controller.finishLoad(success: false);
          }));
    }

  }

  void spFunCalcCheckCount({bool isBtn:false}) {

    spProListValue.forEach((list){
      list.forEach((item){
        if(spProSelectAll){
          item.check=true;
        }
        if(spProSelectAllNot){
          item.check=!item.check;
        }
      });
    });
    setState(() {});
  }

}
